package com.cloudy.impl;


import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;


import org.xml.sax.SAXException;

import com.cloudy.exception.AWSAccessException;
import com.cloudy.exception.S3AccessException;
import com.cloudy.s3.request.S3Request;
import com.cloudy.s3.response.AWSResponse;

public class S3ServiceCaller {
	private static final String COMMA = ",";

	public <T> AWSResponse<T> callService(S3Request request) throws AWSAccessException{		
		SuccessHandler successHandler = request.getSuccessHandler();
		S3ErrorResponseHandler errorHandler = new S3ErrorResponseHandler();
        HttpURLConnection httpConnection = null;
       try{
    	   String hostName="s3.amazonaws.com";
    	   if(request.getBucket()!=null && request.getBucket()!="")
    		   hostName = request.getBucket()+"."+hostName;
//    	   System.out.println("QueryString:"+request.getQueryString());
    	   URL url = new URL("http",hostName,80,"/"+request.getQueryString());
    	   httpConnection = (HttpURLConnection) url.openConnection();
    	   httpConnection.setDoInput(true);
    	   httpConnection.setDoOutput(true);
    	   httpConnection.setUseCaches(false);
    	   httpConnection.setDefaultUseCaches(false);
    	   httpConnection.setAllowUserInteraction(true);
    	   httpConnection.setRequestMethod(request.getRequestMethod());
    	   httpConnection.setRequestProperty("Date", request.getTimeStamp());
    	   httpConnection.setRequestProperty("Authorization", request.getSignature());
    	   for(String key: request.getHeaders().keySet()){
    		   List<String> values = request.getHeaders().get(key);
    		   StringBuilder stringBuilder = new StringBuilder("");
    		   for (String string : values) {
    			   stringBuilder.append(string).append(COMMA);
    		   }
    		   String value = stringBuilder.toString();
    		   if(value.endsWith(COMMA))
    			   value = value.substring(0, value.length()-1);
    		   httpConnection.setRequestProperty(key, value);
    	   }
    	   httpConnection.setRequestProperty("content-type", request.getContentType());
    	   if(request.getContentMD5()!=null && request.getContentMD5()!="")
    		   httpConnection.setRequestProperty("content-md5", request.getContentMD5());
    	   if(request.getS3Object()!=null){
    		   S3Object s3Object = request.getS3Object();
    		   httpConnection.setRequestProperty("Content-Length", String.valueOf(s3Object.getContentLength()));
	    	  
	    	   
	    	   
	    	   s3Object.writeContentToOutPutStream(httpConnection.getOutputStream());
    	   }
    	   httpConnection.connect();
    	   if(httpConnection.getResponseCode()/100 != 2){
    		   if(httpConnection.getErrorStream()!=null)
    			   errorHandler.handleException(httpConnection.getErrorStream());
    		   else{
    			   throw new S3AccessException(httpConnection.getResponseCode()+": "+httpConnection.getResponseMessage());
    		   }
    	   }
    	   return successHandler.handle(httpConnection);
		} catch (Exception e) {
			throw new S3AccessException(e);
		}
	}
}